package com.event.content;

import java.io.IOException;
import java.lang.reflect.Field;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.example.logindesign.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class EventDetailActivity extends Activity {
	private static final String NAMESPACE = "http://tempuri.org/";
	private static final String ENDPOINT = "192.168.1.198:1536/CommunitySystemsicWsWF.asmx";

	// 按钮3个
	private ImageButton btnBack, btnDelete, btnDispose;
	
	// textview控件 15个
	private TextView textViewSjlx;
	private TextView textViewSjlb;
	private TextView textViewClfs;
	private TextView textViewSjrs;
	private TextView textViewFxcs;
	private TextView textViewDsr;
	private TextView textViewLxfs;
	private TextView textViewSjms;
	private TextView textViewDjr;
	private TextView textViewDjsj;
	private TextView textViewLrr;
	private TextView textViewLrjg;
	private TextView textViewSswg;
	private TextView textViewClr;
	private TextView textViewClyj;

	// TextView的变量值
	private String unitcode;
	private String userid;
	private String eventID;
	private String textViewSjlxValue = "";
	private String textViewSjlbValue = "";
	private String textViewClfsValue = "";
	private String textViewSjrsValue = "";
	private String textViewFxcsValue = "";
	private String textViewDsrValue = "";
	private String textViewLxfsValue = "";
	private String textViewSjmsValue = "";
	private String textViewDjrValue = "";
	private String textViewDjsjValue = "";
	private String textViewLrrValue = "";
	private String textViewLrjgValue = "";
	private String textViewSswgValue = "";
	private String textViewClrValue = "";
	private String textViewClyjValue = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_event_detail);
		// sharedpreference中取得相应值
		getValueFromSharedPreferences();
		// 初始化TextView
		initTextView();
	}

	/**
	 * sharedpreference中取得相应值
	 */
	private void getValueFromSharedPreferences() {
		// TODO Auto-generated method stub
		SharedPreferences sharedPreferences = getSharedPreferences("UserInfo",
				Activity.MODE_PRIVATE);
		userid = sharedPreferences.getString("userid", "");
		unitcode = sharedPreferences.getString("unitcode", "");
	}

	/**
	 * 初始化TextView及button
	 */
	private void initTextView() {
		// TODO Auto-generated method stub
		// findviewbyid
		textViewSjlx = (TextView) findViewById(R.id.textView_event_Sjlx);
		textViewSjlb = (TextView) findViewById(R.id.textView_event_Sjlb);
		textViewSjrs = (TextView) findViewById(R.id.textView_event_Sjrs);
		textViewFxcs = (TextView) findViewById(R.id.textView_event_Fxcs);
		textViewDsr = (TextView) findViewById(R.id.textView_event_Dsr);
		textViewLxfs = (TextView) findViewById(R.id.textView_event_Lxfs);
		textViewSjms = (TextView) findViewById(R.id.textView_event_Sjms);
		textViewDjr = (TextView) findViewById(R.id.textView_event_Djr);
		textViewDjsj = (TextView) findViewById(R.id.textView_event_Djsj);
		textViewLrr = (TextView) findViewById(R.id.textView_event_Lrr);
		textViewLrjg = (TextView) findViewById(R.id.textView_event_Lrjg);
		textViewSswg = (TextView) findViewById(R.id.textView_event_Sswg);
		textViewClfs = (TextView) findViewById(R.id.textView_event_Clfs);
		textViewClr = (TextView) findViewById(R.id.textView_event_Clr);
		textViewClyj = (TextView) findViewById(R.id.textView_event_Clyj);

		// setText 耗时的操作放到线程里去
		new setTextViewValueTask().execute();

		// 四个按钮
		btnBack = (ImageButton) findViewById(R.id.btn_event_back);
		btnDelete = (ImageButton) findViewById(R.id.imageButton_event_delete);
		btnDispose = (ImageButton) findViewById(R.id.imageButton_event_dispose);

		// 返回按钮
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 跳转到listview页面
				Intent intent = new Intent();
				intent.setClass(EventDetailActivity.this,
						EventListViewActivity.class);
				startActivity(intent);
			}
		});
		// 删除按钮
		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 弹出对话框 确认取消
				AlertDialog.Builder builder = new AlertDialog.Builder(
						EventDetailActivity.this);
				View view = View.inflate(EventDetailActivity.this,
						R.layout.alertdialog_delete, null);
				builder.setView(view);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setTitle("提示");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								// 删除线程
								new deleteDataTask().execute();
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						});
				Dialog dialog = builder.create();
				dialog.show();
			}
		});
		// 处理按钮
		btnDispose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 跳转到Dispose页面
				skipEditActivity();
			}
		});
	}

	private class deleteDataTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String resultString = deleteData();
			try {
				JSONArray jsonArray = new JSONArray(resultString);
				JSONObject jsonObject = jsonArray.optJSONObject(0);
				if (jsonObject.optString("Code").equals("1")) {
					return "success";
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "fail";
			}
			return "fail";
		}

		protected void onPostExecute(String finallyResultString) {
			if (finallyResultString.equals("success")) {
				Toast.makeText(EventDetailActivity.this, "删除成功",
						Toast.LENGTH_LONG).show();
				// 跳转到listview页面
				skipListViewActivity();
			} else {
				Toast.makeText(EventDetailActivity.this, "删除失败",
						Toast.LENGTH_LONG).show();
			}

		}
	}

	/**
	 * 设置textView的值
	 */
	private class setTextViewValueTask extends AsyncTask<Void, Void, String> {

		protected void onPreExecute() {
			// 设置TextView的值
			setTextViewValue();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// 事件详细参数需要 id,unitcode
			Intent getdetail = getIntent();
			eventID = getdetail.getStringExtra("eventID");
			String resultString = getData();
			Log.e("webservice取得", "完毕");
			String finallyResultString = jsonFormat(resultString);
			return finallyResultString;
		}

		protected void onPostExecute(String finallyResultString) {
			if (finallyResultString.equals("success")) {
				// 设置TextView的值
				setTextViewValue();
			}
		}

	}

	/**
	 * 删除信息
	 * 
	 * @return
	 */
	private String deleteData() {
		// TODO Auto-generated method stub
		String resultString = "";
		String methodName = "del_SysGridMyEvent";
		String soapAcion = "http://tempuri.org/del_SysGridMyEvent";
		SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
		// 操作人员所属区域编码
		soapObject.addProperty("unitcode", unitcode);

		// 事件管理id
		soapObject.addProperty("userid", userid);

		// 事件管理id
		soapObject.addProperty("id", eventID);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soapObject);
		envelope.dotNet = true;
		HttpTransportSE transportSE = new HttpTransportSE(ENDPOINT);
		try {
			transportSE.call(soapAcion, envelope);
			if (envelope.getResponse() != null) {
				SoapObject object = (SoapObject) envelope.bodyIn;
				resultString = object.getProperty(0).toString();
				Log.e("webservice取得", resultString);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultString;
	}

	/**
	 * 得到详细信息
	 * 
	 * @return
	 */
	private String getData() {
		// TODO Auto-generated method stub
		String resultString = "";
		String methodName = "get_SysGridMyEventDetails";
		String soapAcion = "http://tempuri.org/get_SysGridMyEventDetails";
		SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
		// 操作人员所属区域编码
		soapObject.addProperty("unitcode", unitcode);
		// 事件管理id
		soapObject.addProperty("id", eventID);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soapObject);
		envelope.dotNet = true;
		HttpTransportSE transportSE = new HttpTransportSE(ENDPOINT);
		try {
			transportSE.call(soapAcion, envelope);
			if (envelope.getResponse() != null) {
				SoapObject object = (SoapObject) envelope.bodyIn;
				resultString = object.getProperty(0).toString();
				Log.e("webservice取得", resultString);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultString;
	}

	/**
	 * 解析json数据返回hashmap格式数据
	 * 
	 * @return
	 */
	private String jsonFormat(String resultString) {
		// TODO 由于事件管理详细webservice返回值多写了对中括号，导致数据崩溃，所以先用的固定值
		//resultString = "[{'Code':'1','Msg':'成功!'},{'unitcode':'3707250102','id':'12','shijianleixing':'突发事件','shijianleibie':'围堵单位','shejirenshu':'3','lianxifangshi':'15165605516','faxianchangsuo':'3#','dangshiren':'王瑞','shijianmiaoshu':'测试','dengjiren':'我自己','dengjishijian':'2014-07-23 15:04:57','suoshuwangge':'网格一','lururen':'测试','lurujigou':'故城社区','chuliyijian':'结案件'}]";
		JSONArray jsonArray;
		try {
			jsonArray = new JSONArray(resultString);
			JSONObject jsonObject = jsonArray.optJSONObject(0);
			if (jsonObject.optString("Code").equals("1")) {
				// 根据实际从第2组开始取得有关数据
				jsonObject = jsonArray.optJSONObject(1);
				textViewSjlxValue = jsonObject.optString("shijianleixing");
				textViewSjlbValue = jsonObject.optString("shijianleibie");
				textViewSjrsValue = jsonObject.optString("shijirenshu");
				textViewLxfsValue = jsonObject.optString("lianxifangshi");
				textViewFxcsValue = jsonObject.optString("faxianchangsuo");
				textViewDsrValue = jsonObject.optString("dangshiren");
				textViewSjmsValue = jsonObject.optString("shijianmiaoshu");
				textViewDjrValue = jsonObject.optString("dengjiren");
				textViewDjsjValue = jsonObject.optString("dengjishijian");
				textViewSswgValue = jsonObject.optString("suoshuwangge");
				textViewLrrValue = jsonObject.optString("lururen");
				textViewLrjgValue = jsonObject.optString("lurujigou");
				textViewClyjValue = jsonObject.optString("chuliyijian");
				return "success";
			} else {
				return "fail";
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "fail";
	}

	/**
	 * 设置TextView的值
	 */
	private void setTextViewValue() {
		// TODO Auto-generated method stub
		textViewSjlx.setText(textViewSjlxValue);
		textViewSjlb.setText(textViewSjlbValue);
		textViewClfs.setText(textViewClfsValue);
		textViewSjrs.setText(textViewSjrsValue);
		textViewFxcs.setText(textViewFxcsValue);
		textViewDsr.setText(textViewDsrValue);
		textViewLxfs.setText(textViewLxfsValue);
		textViewSjms.setText(textViewSjmsValue);
		textViewDjr.setText(textViewDjrValue);
		textViewDjsj.setText(textViewDjsjValue);
		textViewLrr.setText(textViewLrrValue);
		textViewLrjg.setText(textViewLrjgValue);
		textViewSswg.setText(textViewSswgValue);
		textViewClr.setText(textViewClrValue);
		textViewClyj.setText(textViewClyjValue);
	}

	/**
	 * 设定即使手机物理menu键，仍显示overflow按钮
	 */
	private void forceShowOverflowMenu() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			if (menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(config, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 跳转到listview页面
	 */
	private void skipListViewActivity() {
		Intent listviewIntent = new Intent();
		listviewIntent.setClass(EventDetailActivity.this,
				EventListViewActivity.class);
		EventDetailActivity.this.startActivity(listviewIntent);
		EventDetailActivity.this.finish();
	}

	/**
	 * 跳转到编辑页面，并传入相应参数和标识
	 */
	private void skipEditActivity() {
		Intent editIntent = new Intent();
		editIntent.putExtra("operateFlag", "Edit");
		editIntent.putExtra("enentID", eventID);
		editIntent.putExtra("shijianleixing", textViewSjlxValue);
		editIntent.putExtra("shijianleibie", textViewSjlbValue);
		editIntent.putExtra("shejirenshu", textViewSjrsValue);
		editIntent.putExtra("lianxifangshi", textViewLxfsValue);
		editIntent.putExtra("faxianchangsuo", textViewFxcsValue);
		editIntent.putExtra("dangshiren", textViewDsrValue);
		editIntent.putExtra("shijianmiaoshu", textViewSjmsValue);
		editIntent.putExtra("dengjiren", textViewDjrValue);
		editIntent.putExtra("dengjishijian", textViewDjsjValue);
		editIntent.putExtra("suoshuwangge", textViewSswgValue);
		editIntent.putExtra("lururen", textViewLrrValue);
		editIntent.putExtra("lururenjigou", textViewLrjgValue);
		editIntent.putExtra("chuliyijian", textViewClyjValue);

		editIntent.setClass(EventDetailActivity.this, EventEditActivity.class);
		EventDetailActivity.this.startActivity(editIntent);
		EventDetailActivity.this.finish();
	}

	/**
	 * 重写keydown事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			skipListViewActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
